<template>
  <el-container>
    <el-header>
      <TopBar />
  </el-header>
  <el-main class="el-main">
    <div class="content">
      <div class="user-info-card">
        <div class="userinfo">
          <div class="avatar-container">
            <img :src="user.avatar ? `http://localhost:5000/uploads/${user.avatar}` : 'src/assets/touxiang.png'" alt="用户头像" class="avatar" />
            <div class="avatar-overlay" @click="openAvatarModal">
              <i class="el-icon-camera"></i>
              <span>更换头像</span>
            </div>
          </div>
          <div class="user-details">
            <h2 class="username">{{ user.username }}</h2>
            <p>年龄: {{ calculateAge(user.birthday) }}</p>
            <p>性别: {{ user.gender }}</p>
            <p>学校: {{ schoolName }}</p>
            <p>加入社团数: {{ user.clubs.length }}</p>
            <p>个性签名: {{ user.signature }}</p>
            <button @click="openEditModal" class="edit-button">修改资料</button>
          </div>
        </div>
      </div>
      <h2>发布的帖子</h2>
      <div class="post-waterfall-wrapper">
        <PostWaterfall
          ref="postWaterfall"
          :posts="posts"
          sortBy="createdAt"
          sortOrder="desc"
          :columns="0"
          :hasMore="false"
          @post-click="openPostDetail"
        />
      </div>
    </div>

    <div v-if="isEditModalOpen" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeEditModal">&times;</span>
        <h2>修改资料</h2>
        <form @submit.prevent="submitEdit" class="edit-form">
          <label for="username">用户名:</label>
          <input v-model="editUser.username" id="username" type="text" />

          <label for="birthday">出生日期:</label>
          <input v-model="editUser.birthday" id="birthday" type="date" />

          <label for="gender">性别:</label>
          <select v-model="editUser.gender" id="gender">
            <option value="">选择性别</option>
            <option value="男">男</option>
            <option value="女">女</option>
          </select>
          <label for="signature">个性签名:</label>
          <textarea v-model="editUser.signature" id="signature" maxlength="30" @input="checkSignatureLength"></textarea>
          <p v-if="signatureError" class="error-message">{{ signatureError }}</p>

          <button type="submit" class="submit-button">提交</button>
        </form>
      </div>
    </div>

    <PostDetailModal v-if="selectedPost" :post="selectedPost" @close="selectedPost = null" />

    <!-- 头像上传和裁切弹窗 -->
    <div v-if="isAvatarModalOpen" class="modal">
      <div class="modal-content avatar-modal-content">
        <span class="close" @click="closeAvatarModal">&times;</span>
        <h2>修改头像</h2>

        <div v-if="!imageUrl" class="avatar-upload-container">
          <input
            type="file"
            accept="image/*"
            id="avatarUpload"
            ref="avatarInput"
            @change="onFileSelected"
            class="hidden-input"
          />
          <label for="avatarUpload" class="upload-label">
            <i class="el-icon-plus"></i>
            <span>选择图片</span>
          </label>
        </div>

        <div v-if="imageUrl" class="cropper-container">
          <Cropper
            ref="cropper"
            :src="imageUrl"
            :stencil-props="{
              aspectRatio: 1
            }"
            :resize-image="{
              touch: true,
              wheel: {
                ratio: 0.1
              }
            }"
            class="cropper-view"
            @change="onChange"
          />

          <div class="cropper-buttons">
            <button @click="resetImage" class="reset-button">重置</button>
            <button @click="uploadAvatar" class="submit-button">保存头像</button>
          </div>
        </div>
      </div>
    </div>

</el-main>
</el-container>
</template>

<script setup>
import TopBar from '../components/TopBar.vue'
import PostDetailModal from '../components/PostDetailModal.vue'
import PostWaterfall from '../components/PostWaterfall.vue'
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'
import { Cropper } from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const selectedPost = ref(null);
const schoolName = ref(''); // 存储学校名称

const user = ref({
  avatar: '',
  username: '',
  age: '',
  gender: '',
  school: '',
  clubs: [],
  signature: '',
  birthday: ''
});

const posts = ref([]);
const isEditModalOpen = ref(false);
const editUser = ref({
  username: '',
  birthday: '',
  gender: '',
  school: '',
  signature: ''
});

const signatureError = ref('');
const postWaterfall = ref(null);
const isAvatarModalOpen = ref(false);
const imageUrl = ref('');
const avatarInput = ref(null);
const cropper = ref(null);
const cropperState = ref(null);

const router = useRouter();

function calculateAge(birthday) {
  if (!birthday) return '';
  const birthDate = new Date(birthday);
  const ageDiff = Date.now() - birthDate.getTime();
  const ageDate = new Date(ageDiff);
  return Math.abs(ageDate.getUTCFullYear() - 1970);
}

function openEditModal() {
  editUser.value = { ...user.value };
  isEditModalOpen.value = true;
}

function closeEditModal() {
  isEditModalOpen.value = false;
}

async function submitEdit() {
  try {
    const token = localStorage.getItem('token');
    await axios.put('http://localhost:5000/users/me', editUser.value, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    Object.assign(user.value, editUser.value);
    closeEditModal();
  } catch (error) {
    console.error('更新用户信息失败:', error);
  }
}

// 根据学校ID获取学校名称
async function fetchSchoolName(schoolId) {
  if (!schoolId) {
    schoolName.value = '未设置';
    return;
  }

  try {
    const response = await axios.get(`http://localhost:5000/school/${schoolId}`);
    if (response.data && response.data.name) {
      schoolName.value = response.data.name;
    } else {
      schoolName.value = '未知学校';
    }
  } catch (error) {
    console.error('获取学校信息失败:', error);
    schoolName.value = '获取学校信息失败';
  }
}

async function fetchUserProfile() {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    const response = await axios.get('http://localhost:5000/users/me', {
      headers: {
        Authorization: `Bearer ${token}` // 将 token 添加到请求头
      }
    });
    user.value = response.data; // 假设返回的数据结构与 user 对象匹配
    console.log('用户信息：', user.value);

    // 获取学校名称
    if (user.value.school) {
      await fetchSchoolName(user.value.school);
    }

    // 获取用户发布的帖子
    const postsResponse = await axios.get(`http://localhost:5000/users/${user.value._id}/posts`, {
      headers: {
        Authorization: `Bearer ${token}` // 将 token 添加到请求头
      }
    });
    posts.value = postsResponse.data;

    // 在数据加载后，重新计算瀑布流布局
    nextTick(() => {
      if (postWaterfall.value) {
        setTimeout(() => {
          postWaterfall.value.calculateColumns();
          postWaterfall.value.resizeAllWaterfallItems();
        }, 200);
      }
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
}

function checkSignatureLength() {
  if (editUser.value.signature.length > 30) {
    signatureError.value = '个性签名不能超过30个字符';
  } else {
    signatureError.value = '';
  }
}

function openPostDetail(post) {
  selectedPost.value = post;
}

function openAvatarModal() {
  isAvatarModalOpen.value = true;
}

function closeAvatarModal() {
  isAvatarModalOpen.value = false;
}

function onFileSelected(event) {
  const file = event.target.files[0];
  console.log('选择了文件:', file ? file.name : '无文件');

  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      console.log('文件读取完成, 数据长度:', e.target.result.length);
      imageUrl.value = e.target.result;
    };
    reader.onerror = (e) => {
      console.error('文件读取失败:', e);
    };
    reader.readAsDataURL(file);
  }
}

function resetImage() {
  imageUrl.value = '';
}

// 监听裁剪变化
function onChange({ coordinates, canvas }) {
  console.log('裁剪变化', coordinates);
  cropperState.value = { coordinates, canvas };
}

async function uploadAvatar() {
  try {
    // 获取裁剪后的图片
    const cropperRef = cropper.value;
    console.log('裁剪器实例:', cropperRef);

    if (!cropperRef) {
      console.error('裁剪器实例不存在');
      return;
    }

    // 获取裁剪结果
    const { canvas } = cropperRef.getResult();
    if (!canvas) {
      console.error('获取裁剪数据失败');
      return;
    }

    // 将canvas转为blob
    canvas.toBlob(async (blob) => {
      if (!blob) {
        console.error('Canvas转Blob失败');
        return;
      }

      console.log('获取到裁剪的blob数据，大小:', blob.size);

      const token = localStorage.getItem('token');

      // 创建文件对象
      const file = new File([blob], 'avatar.png', { type: 'image/png' });

      // 创建表单数据
      const formData = new FormData();
      formData.append('avatar', file);

      try {
        // 发送到服务器
        const response = await axios.post('http://localhost:5000/users/me/avatar', formData, {
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'multipart/form-data'
          }
        });

        // 更新用户头像
        user.value.avatar = response.data.avatar;

        // 关闭模态框并重置状态
        closeAvatarModal();
        resetImage();

        // 显示成功消息
        alert('头像上传成功！');
        location.reload();
      } catch (error) {
        console.error('上传头像失败:', error);
        alert('上传头像失败，请重试');
      }
    }, 'image/png');
  } catch (error) {
    console.error('裁剪头像失败:', error);
    alert('裁剪头像失败，请重试');
  }
}

onMounted(async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  fetchUserProfile();
});
</script>

<style>
body {
  background-color: #1f1b24;
  margin: 0;
  padding: 0;
}
::-webkit-scrollbar{
  display: none;
}

.content {
  position: absolute;
  top: 60px;
  left: 10vw;
  right: 10vw;
  bottom: 0;
  padding: 20px;
  overflow-y: auto;
}

.post-waterfall-wrapper {
  width: 100%;
}

.user-info-card {
  background-color: #28232e;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  margin-bottom: 30px;
  color: #ffffff;
  position: relative;
  overflow: hidden;
}

/* 装饰元素 */
.user-info-card::before {
  content: "";
  position: absolute;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: linear-gradient(45deg, #3f51b5, #2196f3);
  opacity: 0.1;
  top: -100px;
  right: -100px;
  z-index: 0;
}

.user-info-card::after {
  content: "";
  position: absolute;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background: linear-gradient(45deg, #9c27b0, #e91e63);
  opacity: 0.1;
  bottom: -75px;
  left: -75px;
  z-index: 0;
}

.userinfo {
  display: flex;
  align-items: center;
  position: relative;
  z-index: 1;
}

.avatar-container {
  position: relative;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  margin-right: 40px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
  border: 4px solid rgba(255, 255, 255, 0.1);
  object-fit: cover;
  transition: transform 0.3s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
}

.avatar-overlay i {
  font-size: 24px;
  margin-bottom: 8px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.user-details {
  text-align: left;
  width: 600px;
}

.username {
  font-size: 32px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #ffffff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.user-details p {
  font-size: 16px;
  line-height: 1.6;
  color: #b0bec5;
  margin: 8px 0;
}

h2 {
  color: #ffffff;
  font-size: 28px;
  margin: 30px 0 20px;
  font-weight: 600;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  backdrop-filter: blur(5px);
}

.modal-content {
  background-color: #28232e;
  padding: 40px;
  border-radius: 16px;
  width: 500px;
  position: relative;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
  color: #ffffff;
}

.close {
  position: absolute;
  top: 15px;
  right: 25px;
  cursor: pointer;
  font-size: 30px;
  color: #b0bec5;
  transition: color 0.3s ease;
}

.close:hover {
  color: #e91e63;
}

.edit-button {
  background: linear-gradient(45deg, #3f51b5, #2196f3);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 20px;
  cursor: pointer;
  font-weight: 600;
  margin-top: 15px;
  transition: all 0.3s ease;
  display: inline-block;
}

.edit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(33, 150, 243, 0.3);
}

.edit-form {
  display: flex;
  flex-direction: column;
}

.edit-form label {
  margin: 15px 0 8px;
  color: #b0bec5;
  font-size: 14px;
}

.edit-form input,
.edit-form select,
.edit-form textarea {
  padding: 12px 16px;
  border: 1px solid #424242;
  border-radius: 8px;
  margin-bottom: 5px;
  background: #333333;
  color: #ffffff;
  font-size: 14px;
  transition: all 0.3s ease;
}

.edit-form input:focus,
.edit-form select:focus,
.edit-form textarea:focus {
  border-color: #3f51b5;
  outline: none;
  box-shadow: 0 0 0 2px rgba(63, 81, 181, 0.2);
}

.edit-form button {
  margin-top: 25px;
  padding: 12px;
  background: linear-gradient(45deg, #3f51b5, #2196f3);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
}

.edit-form button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(33, 150, 243, 0.3);
}

.error-message {
  color: #f44336;
  font-size: 13px;
  margin-top: 4px;
}

/* 头像上传相关样式 */
.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
}

.avatar-overlay i {
  font-size: 24px;
  margin-bottom: 8px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-modal-content {
  width: 550px;
  max-width: 90vw;
}

.hidden-input {
  display: none;
}

.avatar-upload-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px 0;
}

.upload-label {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  border: 2px dashed #424242;
  border-radius: 12px;
  cursor: pointer;
  color: #b0bec5;
  transition: all 0.3s ease;
}

.upload-label:hover {
  border-color: #3f51b5;
  color: #3f51b5;
}

.upload-label i {
  font-size: 36px;
  margin-bottom: 10px;
}

.cropper-container {
  padding: 20px 0;
}

.cropper-view {
  height: 350px;
  background: #000;
}

.cropper-buttons {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 16px;
}

.reset-button {
  background: #424242;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 20px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
}

.reset-button:hover {
  background: #616161;
}

/* 响应式布局 */
@media (max-width: 699px) {
  .content {
    left: 5vw;
    right: 5vw;
  }
}
</style>
